<?php

namespace app\common\service\ai;

use think\facade\Db;
use app\common\service\CommonService;

/**
 * 订单
 */
class OrderService extends CommonService {

    /**
     * 表名
     * @static string
     */
    protected static $table = 'order';

    /**
     * 创建订单号
     * @param string $prefix 前缀
     * @return string
     */
    public static function createOrerNo($prefix = 'NO') {
        return $prefix . date('YmdHis') . getRandomString('numeric', 6);
    }

    /**
     * 列表
     * @param array $data 数据
     * @return array
     */
    public static function getList($data) {
        $list = self::query(self::$table)->_equal('member_id,type')->order('id desc')->_page();
        return $list;
    }

    /**
     * 列表
     * @param array $data 数据
     * @return array
     */
    public static function getListByHome($data) {
        $list = self::query(self::$table)
            ->_equal('member_id,type')
            ->_dateBetween('create_time')
            ->order('id desc')
            ->_page(true);
        return $list;
    }

    /**
     * 列表
     * @param array $data 数据
     * @return array
     */
    public static function getListByAdmin($data) {
        $list = self::query(self::$table)
            ->leftJoin('member m', 'm.member_id = a.member_id')
            ->_equal('a.type#type,m.nickname#nickname,m.username#username,m.phone#phone,m.member_id#member_id')
            ->_dateBetween('a.create_time#create_time')
            ->order('a.id desc')
            ->field('a.*,m.phone')
            ->_page(true);
        return $list;
    }

    /**
     * 列表
     * @param array $data 数据
     * @return array
     */
    public static function getPointPriceList($data) {
        $list = self::query('point_price')->order('sale_price')->_select();
        return $list;
    }

    /**
     * 提交
     * @param array $data 数据
     * @param int $type 类型(开户0,1充值,2扣点)
     * @param int $ai_type AI类型(0视频,1音频,2音色)
     * @param int $scene_type 场景类型(0后台,1会员)
     * @return array
     */
    public static function submit($data, $type = 0, $ai_type = 0, $scene_type = 0) {
        $member = self::query('member')->where(['member_id' => $data['member_id']])->_find();
        !$member && exception('会员不存在');
        Db::startTrans();
        // 订单
        $order_no = OrderService::createOrerNo();
        $point_rate = SystemConfigService::getDetail('POINT_EXCHANGE')['value'] ?: 10;
        $point = $data['sale_price'] * $point_rate;
        $order_data = [
            'order_no' => $order_no,
            'member_id' => $data['member_id'],
            'type' => $type,
            'scene_type' => $scene_type,
            'point' => $point,
            'sale_price' => $data['sale_price'],
            'point_rate' => $point_rate,
            'before_point' => $member['remain_point'],
            'after_point' => $member['remain_point'] + $point,
            'remark' => self::getRemark($type, $ai_type, $scene_type),
        ];
        $order_id = self::model()->_insert('order', $order_data);
        if (!$order_id) {
            Db::rollback();
            exception();
        }
        // 用户充点
//        $result = self::model()->_update('member', ['point' => Db::raw("point+{$point}"), 'remain_point' => Db::raw("remain_point+{$point}")], ['member_id' => $data['member_id']]);
//        if (!$result) {
//            Db::rollback();
//            exception();
//        }
        Db::commit();
        self::success(['order_no' => $order_no]);
    }

    /**
     * 统计
     * @param array $data 数据
     * @return array
     */
    public static function count($data) {
        $field = "
            IFNULL(SUM(IF(type=1,point,0)),0) add_point,
            IFNULL(SUM(IF(type=2,point,0)),0) reduce_point,
            IFNULL(SUM(IF(ai_type=0,point,0)),0) video_point,
            IFNULL(SUM(IF(ai_type=1,point,0)),0) voice_point";
        // 当天数据
        $day_member_num = self::query('member')->where(['is_delete' => 0])->whereRaw('DATE(create_time) = CURDATE()')->_count('member_id');
        $day = self::query(self::$table)->whereRaw('DATE(create_time) = CURDATE()')->_find($field);
        // 历史数据
        $history_member_num = self::query('member')->where(['is_delete' => 0])->_count('member_id');
        $history = self::query(self::$table)->where('1=1')->_find($field);
        return [
            'day' => [
                'member_num' => $day_member_num,
                'add_point' => $day['add_point'],
                'reduce_point' => $day['reduce_point'],
                'video_point' => $day['video_point'],
                'voice_point' => $day['voice_point'],
            ],
            'history' => [
                'member_num' => $history_member_num,
                'add_point' => $history['add_point'],
                'reduce_point' => $history['reduce_point'],
                'video_point' => $history['video_point'],
                'voice_point' => $history['voice_point'],
            ]
        ];
    }

    /**
     * 备注
     * @param int $type 类型(开户0,1充值,2扣点)
     * @param int $ai_type AI类型(0视频,1音频,2音色)
     * @param int $scene_type 场景类型(0后台,1会员)
     * @return string
     */
    public static function getRemark($type = 0, $ai_type = 0, $scene_type = 0) {
        $remark = null;
        if ($type == 0) {
            $remark = $scene_type == 0 ? '后台会员开户' : '会员开户';
        } else if ($type == 1) {
            $remark = $scene_type == 0 ? '后台会员充点' : '会员充点';
        } else if ($type == 2) {
            $remark = $scene_type != 0 ? ($ai_type == 1 ? '合成AI视频扣点' : ($ai_type == 2 ? '合成AI音频扣点' : '购买音色扣点')) : '后台会员扣点';
        }
        return $remark;
    }

    /**
     * 处理
     * @param array $data 数据(必传member_id会员ID,扩展参数[type=1(scene_type=0传point点数,scene_type=1传sale_price充值金额),type=2(ai_type=0传video_id视频ID,ai_type=1传voice_id音频ID,ai_type=2传speaker_id音色ID)])
     * @param int $type 类型(开户0,1充值,2扣点)
     * @param int $ai_type AI类型(0视频,1音频,2音色)
     * @param int $scene_type 场景类型(0后台,1会员)
     * @return array
     */
    public static function handle($data, $type = 0, $ai_type = 0, $scene_type = 0) {
        // 会员
        $member_id = $data['member_id'];
        $member_point = self::query('member')->where(['member_id' => $member_id])->_value('remain_point');
        if (!$member_point) {
            return self::error_out('会员不存在');
        }
        // 订单
        list($sale_price, $point, $point_rate) = [$data['sale_price'] ?? 0, $data['point'] ?? 0, 0];
        if ($type == 0) { // 开户
            $sale_price = SystemConfigService::getDetail('OPEN_ACCOUNT_FEE')['value'] ?: 0;
            $point_rate = SystemConfigService::getDetail('POINT_EXCHANGE')['value'] ?: 10;
            $point = $sale_price * $point_rate;
        }
        if ($type == 1 && $scene_type == 1) { // 充点
            $point_rate = SystemConfigService::getDetail('POINT_EXCHANGE')['value'] ?: 10;
            $point = $sale_price * $point_rate;
        }
        if ($member_point < $point) {
            return self::error_out('会员点数不够');
        }
        $op = $type == 2 ? '-' : '+';
        $order_no = OrderService::createOrerNo();
        $order_data = [
            'order_no' => $order_no,
            'status' => 1,
            'pay_time' => datetime(),
            'member_id' => $member_id,
            'type' => $type,
            'ai_type' => $ai_type,
            'scene_type' => $scene_type,
            'video_id' => $data['video_id'] ?? 0,
            'voice_id' => $data['voice_id'] ?? 0,
            'speaker_id' => $data['speaker_id'] ?? 0,
            'point' => $point,
            'sale_price' => $sale_price,
            'point_rate' => $point_rate,
            'before_point' => $member_point,
            'after_point' => eval("return {$member_point}{$op}{$point};"),
            'remark' => self::getRemark($type, $ai_type, $scene_type),
        ];
        $order_id = self::model()->_insert(self::$table, $order_data);
        if (!$order_id) {
            return self::error_out();
        }
        // 用户点数
        if ($type == 2) {
            $user_data = ['remain_point' => Db::raw("remain_point{$op}{$point}")];
        } else {
            $user_data = ['point' => Db::raw("point{$op}{$point}"), 'remain_point' => Db::raw("remain_point{$op}{$point}")];
        }
        $result = self::model()->_update('member', $user_data, ['member_id' => $member_id]);
        if (!$result) {
            return self::error_out();
        }
        return self::success_out();
    }

    /**
     * 详情
     * @param array $data 数据
     * @return array
     */
    public static function getDetail($orderNo) {
        return self::query(self::$table)->where(['order_no' => $orderNo])->_find();
    }
    
    /**
     * 支付回调
     * @param string $order_no 订单号
     * @return array
     */
    public static function callback($order_no) {
        Db::startTrans();
        // 订单
        $order = self::query(self::$table)->where(['order_no' => $order_no, 'status' => 0])->_find();
        if (!$order) {
            return self::error_out('订单不存在');
        }
        $order_result = self::model()->_update(self::$table, ['status' => 1, 'pay_time' => datetime()], ['order_no' => $order_no]);
        if (!$order_result) {
            Db::rollback();
            return self::error_out('更新订单失败');
        }
        // 用户充点
        list($member_id, $point) = [$order['member_id'], $order['point']];
        $result = self::model()->_update('member', ['point' => Db::raw("point+{$point}"), 'remain_point' => Db::raw("remain_point+{$point}")], ['member_id' => $member_id]);
        if (!$result) {
            Db::rollback();
            return self::error_out('更新用户失败');
        }
        Db::commit();
        return self::success_out();
    }

}
